<?php defined('BASEPATH') OR die('No direct access allowed.');
/**
 * Description of "Accounts_model"
 *
 * Created on Jan. 17, 2010
 * @author Ramon Gutierrez
 * @copyright Bitstop Network Services Inc.
 * @version 0.1
 */

class Accounts_model extends Model {
	public function Accounts_model() {
		global $table;
        parent::Model();
		$this->CI =& get_instance();
		$table = 'accounts';
    }
	
	// Get all items
	public function getAll($client_id = false) {
		global $table;
		$query = $this->db->query("SELECT id, account_id, name, street_address, city, state, country_id, zip, contact_number FROM $table " . ($client_id ? "WHERE client_id = $client_id" : "") . " ORDER BY post_date DESC");
		return $query;
	}
	
	// Get company name of account
	public function getCompanyName($id) {
		$query = $this->db->query("SELECT c.name AS company FROM clients c, accounts a WHERE a.id = " . $id . " AND a.id = c.account_id LIMIT 1");
		$row = $query->row();
		return $row->company;
	}
	
	// Check if user is allowed to edit/delete said account
	public function checkAuth($id, $client_id, $account_type) {
		if($account_type == 'manager') {
			$query = $this->db->select('a.id')
							  ->where('b.account_id = a.id')
							  ->where('b.client_id', $client_id)
							  ->get('branches b, accounts a');
		} else if($account_type == 'agent') {
			$query = $this->db->select('a.id')
							  ->where('g.account_id = a.id')
							  ->where('g.client_id', $client_id)
							  ->get('agents g, accounts a');
		} else {
			return false;
		}
		
		return $query->num_rows();
	}
	
	// Get agent information
	public function getAgentInfo($id) {
		$query1 = $this->db->select('id, branch_id')->where('account_id', $id)->get('agents');
		if($query1->num_rows() > 0) {
			$row = $query1->row();
			$query2 = $this->db->select('client_service_id')->where('agent_id', $row->id)->get('agents_services');
			
			if($query2->num_rows() > 0) {
				$result['agent_id'] = $row->id;
				$result['branch_id'] = $row->branch_id;
				$result['services'] = $query2;
				
				return $result;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}

/* End of file accounts_model.php */
/* Location: ./system/application/models/accounts_model.php */